import request from './request'

export interface AiSolverRequest {
  question: string
  questionType?: string
  context?: string
  userId?: number
}

export interface AiSolverResponse {
  answer: string
  followUpQuestions: string[]
  conversationId: string
  messageId: string
  success: boolean
  error?: string
}

export interface ConversationResponse {
  conversationId: string
  userId: string
}

export const aiSolverApi = {
  // AI解题
  solveQuestion: (data: AiSolverRequest): Promise<AiSolverResponse> => {
    return request.post('/ai-solver/solve', data)
  },
  
  // AI图片解题
  solveQuestionWithImage: (formData: FormData): Promise<AiSolverResponse> => {
    return request.post('/ai-solver/solve-with-image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  
  // 流式AI解题
  solveQuestionStream: async (data: AiSolverRequest): Promise<ReadableStream<Uint8Array>> => {
    console.log('=== 发送流式AI解题请求 ===')
    console.log('请求URL:', '/api/ai-solver/solve-stream')
    console.log('请求数据:', data)
    
    const response = await fetch('/api/ai-solver/solve-stream', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream'
      },
      body: JSON.stringify(data)
    })
    
    console.log('=== 收到响应 ===')
    console.log('响应状态:', response.status)
    console.log('响应状态文本:', response.statusText)
    console.log('响应头:', Object.fromEntries(response.headers.entries()))
    console.log('响应体存在:', !!response.body)
    
    if (!response.ok) {
      const errorText = await response.text()
      console.error('AI流式解题请求失败:', response.status, errorText)
      throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`)
    }
    
    console.log('=== 返回响应体流 ===')
    return response.body!
  },
  
  // 流式AI图片解题
  solveQuestionWithImageStream: async (formData: FormData): Promise<ReadableStream<Uint8Array>> => {
    const response = await fetch('/api/ai-solver/solve-with-image-stream', {
      method: 'POST',
      headers: {
        'Accept': 'text/event-stream'
      },
      body: formData
    })
    
    if (!response.ok) {
      if (response.status === 503) {
        throw new Error('AI服务暂时不可用，请稍后再试')
      }
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return response.body!
  },
  
  // 完整文件处理流程 - 上传文件→检索内容→智能体处理→返回结果
  processFileComplete: async (formData: FormData): Promise<ReadableStream<Uint8Array>> => {
    console.log('=== 开始完整文件处理流程 ===')
    const response = await fetch('/api/ai-solver/process-file-complete', {
      method: 'POST',
      headers: {
        'Accept': 'text/event-stream'
      },
      body: formData
    })
    
    if (!response.ok) {
      if (response.status === 503) {
        throw new Error('AI服务暂时不可用，请稍后再试')
      }
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    console.log('=== 完整文件处理流程响应接收成功 ===')
    return response.body!
  },
  
  // 获取用户对话历史
  getUserConversation: (userId: number): Promise<ConversationResponse> => {
    return request.get(`/ai-solver/conversation/${userId}`)
  },
  
  // 清除用户对话历史
  clearUserConversation: (userId: number): Promise<{ message: string; userId: string }> => {
    return request.delete(`/ai-solver/conversation/${userId}`)
  }
}
